package com.ztstkj.lzscale.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.core.graphics.toColorInt
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.sscl.baselibrary.utils.BigDecimalUtils
import com.sscl.baselibrary.utils.DebugUtil
import com.ztstkj.lzscale.R
import com.ztstkj.lzscale.adpters.CartAdapter
import com.ztstkj.lzscale.adpters.CartItem
import com.ztstkj.lzscale.adpters.RecyleAdapter
import com.ztstkj.lzscale.databinding.ActivityRecyclableBinding
import com.ztstkj.lzservices.cameras.CameraUtil
import com.ztstkj.lzservices.cameras.CameraXManager
import com.ztstkj.lzservices.dto.RecycleOrderInput
import com.ztstkj.lzservices.dto.RecycleOrderItemInput
import com.ztstkj.lzservices.dto.RecyleItem
import com.ztstkj.lzservices.events.EventCard
import com.ztstkj.lzservices.events.EventWeight
import com.ztstkj.lzservices.exceptions.apiCall
import com.ztstkj.lzservices.extension.SpannableStringBuilderExt.appendColorFontSize
import com.ztstkj.lzservices.mmkvs.MmkvManager
import com.ztstkj.lzservices.model.SettlementEnum
import com.ztstkj.lzservices.networks.NetworkUtils
import com.ztstkj.lzservices.retrofits.Api
import com.ztstkj.lzservices.utils.SpeakUtil
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal

class RecyclableActivity : ScaleActivity() {
    private var cameraX: CameraXManager? = null
    private lateinit var binding: ActivityRecyclableBinding
    private lateinit var recyleAdapter: RecyleAdapter
    private var curItem: RecyleItem? = null
    private lateinit var cartAdapter: CartAdapter
    private var curCartItem: CartItem = CartItem()
    private var curCartList: MutableList<CartItem> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_recyclable)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_recyclable)
        init()
        initCameraX()
        getRecyleItem()
        calculateCart()
    }

    @SuppressLint("SetTextI18n")
    private fun init() {
        val eq = MmkvManager.getEquipment()
        curCartItem.settlement = curSetting.settlement
        if (eq != null) {
            //binding.tvSupervisorName.text = eq.supervisorName
            curEquipmentId = eq.id
            curDeptId = eq.deptId
        }
        //*************初始化摄像头
        binding.tvRecyleNoCamera.setOnClickListener {
            DebugUtil.debugOut("检测是否有摄像头")
            if (CameraUtil.isCamera2(baseContext)) {
                initCameraX()
            } else {
                ToastUtils.showLong("未检测到摄像头设备", 3000)
            }
        }
        binding.btnConfirm.setOnClickListener { l ->
            DebugUtil.debugOut("点击")
            if (curItem == null) {
                SpeakUtil.speech(this, "请选择回收物品")
                return@setOnClickListener
            }
            if (curWeight <= 0) {
                SpeakUtil.speech(this, "重量为零")
                return@setOnClickListener
            }
            println(GsonUtils.toJson(curCartItem.deepCopy()))
            //拍照，存储图片的本地路径
            curCartList.add(curCartItem.deepCopy())
            calculateCart()
            initCartItem()
        }
        binding.btnCheckOut.setOnClickListener {
            checkOut()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun calculateCart() {
        if (curCartList.size > 0) {
            if (curCartItem.settlement == SettlementEnum.POINT.value) {
                binding.tvTotal.text =
                    "合计：${curCartList.sumOf { it -> it.productPointAmount }} 积分"
            } else if (curCartItem.settlement == SettlementEnum.CASH.value) {
                binding.tvTotal.text =
                    "合计：${curCartList.sumOf { it -> it.prodcutPriceAmount }} 元"
            }
            binding.tvTotalTip.text = "共计：${curCartList.size} 件"
        } else {
            binding.tvTotal.text = "合计：0 "
            binding.tvTotalTip.text = "共计：0 件"
        }

    }

    @SuppressLint("SetTextI18n")
    private fun initCameraX() {
        if (CameraUtil.isCamera2(baseContext)) {
            cameraX = CameraXManager(this, binding.previewRecyle)
            if (cameraX?.hasBackCamera() == true) {
                cameraX?.initPermission()
                binding.tvRecyleNoCamera.visibility = ViewGroup.GONE
                binding.previewRecyle.visibility = ViewGroup.VISIBLE
            } else {
                binding.tvRecyleNoCamera.visibility = ViewGroup.VISIBLE
                binding.previewRecyle.visibility = ViewGroup.GONE
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventCard(e: EventCard) {
        if (NetworkUtils.onLine) {
            getUserByCard(e.cardNo.toString(), e.modbus)
        } else {
            getUserByCardFromMkv(e.cardNo.toString(), e.modbus)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventWeight(e: EventWeight) {
        curWeight = e.weight
        showWeight(curWeight)
        calculateAmount()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun checkOut() {
        if (curUserId == 0L) {
            SpeakUtil.speech(this, "请刷卡后提交")
            return
        }
        if (curCartList.size <= 0) {
            SpeakUtil.speech(this, "当前没有物品")
            return
        }
        val order = RecycleOrderInput(curUserId, curCard, curSetting.settlement)
        order.totalPrice = curCartList.sumOf { it.productPointAmount }
        val orderItems = curCartList.map { cartItem ->
            val item = RecycleOrderItemInput(cartItem.productId, cartItem.productName)
            if (curSetting.settlement == SettlementEnum.POINT.value){
                item.recylePrice = cartItem.productPoint
                item.total=cartItem.productPointAmount
            }
            if (curSetting.settlement == SettlementEnum.CASH.value){
                item.recylePrice = cartItem.productPrice.toInt()
                item.total=cartItem.prodcutPriceAmount.toInt()
            }
            item.weight=cartItem.productWeight
            item.photo=cartItem.photo
            item
        }
        order.items=orderItems
        lifecycleScope.launch {
            val resp = apiCall(true) { Api.get().postCreateOrder(order) }
            if (resp.success && resp.data==1) {
                curItem=null
                clearCurRecyle()
                curCartList.clear()
                cartAdapter.notifyDataSetChanged()
                calculateCart()
                SpeakUtil.speech(this@RecyclableActivity, "提交成功，一个工作日内审核通过后发放积分")
            }else{
                SpeakUtil.speech(this@RecyclableActivity, "结算失败")
            }
        }
    }

    private fun calculateAmount() {
        if (curItem != null && curWeight > 0) {
            curCartItem.productWeight = curWeight
            if (curSetting.settlement == SettlementEnum.POINT.value) {
                val builder = SpannableStringBuilder()
                builder.append("可获得")
                val curAmount = BigDecimalUtils.mul(
                    curItem!!.point.toString(),
                    BigDecimalUtils.div(curWeight.toString(), 1000.toString(), 2),
                    0
                )
                curCartItem.productPointAmount = curAmount.toInt()
                builder.appendColorFontSize(curAmount.toString(), "#FF4545".toColorInt(), 24)
                builder.append("积分")
                binding.tvCurAmount.text = builder
            }
            if (curSetting.settlement == SettlementEnum.CASH.value) {
                val builder = SpannableStringBuilder()
                builder.append("回收价")
                val curAmount = BigDecimalUtils.mul(
                    curItem!!.price.toString(),
                    BigDecimalUtils.div(curWeight.toString(), 1000.toString(), 2),
                    2
                )
                curCartItem.prodcutPriceAmount = BigDecimal(curAmount)
                builder.appendColorFontSize(curAmount.toString(), "#FF4545".toColorInt(), 24)
                builder.append("元")
                binding.tvCurAmount.text = builder
            }
        } else {
            binding.tvCurAmount.text = ""
            curCartItem.productWeight = 0
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showWeight(weight: Int) {
        if (weight > 1000) {
            binding.tvCurWeightUnit.text = "千克"
            binding.tvCurWeight.text = "%.2f".format(weight.toDouble() / 1000)
        } else {
            binding.tvCurWeightUnit.text = "克"
            binding.tvCurWeight.text = weight.toString()
        }
    }

    private fun getRecyleItem() {
        lifecycleScope.launch {
            val resp = apiCall(false) { Api.get().getRecyles() }
            val data = resp.data
            if (resp.success && data != null) {
                initRecyleItem(data)
            }
        }
    }

    private fun initCartItem() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        val recyclerview = binding.recyclerCarts
        recyclerview.layoutManager = linearLayoutManager
        cartAdapter = CartAdapter(curCartList)
        recyclerview.adapter = cartAdapter
        cartAdapter.onCartItemDel = object : CartAdapter.ICartItemDelClickListener {
            override fun onClick() {
                SpeakUtil.speech(this@RecyclableActivity, "删除成功")
                calculateCart()
            }
        }

    }

    private fun initRecyleItem(datas: List<RecyleItem>) {
        val manager = object : FlexboxLayoutManager(this, FlexDirection.ROW, FlexWrap.WRAP) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        manager.flexWrap = FlexWrap.WRAP;
        manager.flexDirection = FlexDirection.ROW;
        manager.alignItems = AlignItems.CENTER;
        manager.justifyContent = JustifyContent.FLEX_START;
        val recyclerview = binding.recyclerRecyle
        recyclerview.layoutManager = manager
        recyleAdapter = RecyleAdapter(datas, curSetting.settlement)
        recyleAdapter.onClickListener = object : RecyleAdapter.IRecyleItemClickListener {
            @SuppressLint("UseCompatLoadingForDrawables", "SetTextI18n")
            override fun onClick(item: RecyleItem) {
                curItem = item
                curCartItem.productId=item.id
                curCartItem.productName = item.name
                curCartItem.productImage = item.iconName
                curCartItem.productPrice = item.price
                curCartItem.productPoint = item.point
                binding.imgCurRecyle.setImageDrawable(
                    baseContext.getDrawable(
                        baseContext.resources.getIdentifier(
                            item.iconName,
                            "drawable",
                            baseContext.packageName
                        )
                    )
                )
                binding.tvCurRecylePrice.text = item.name + " " + item.curPrice
                this@RecyclableActivity.calculateAmount()
                SpeakUtil.speech(baseContext, item.name)
            }
        }
        recyclerview.adapter = recyleAdapter
    }
    private fun clearCurRecyle(){
        binding.imgCurRecyle.setImageDrawable(null)
        this@RecyclableActivity.calculateAmount()
        binding.tvCurRecylePrice.text=""
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraX?.shutDown()
    }
}